import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/widgets/common_bottom_sheet.dart';
import 'package:casdon/modules/recipe/application/notification/miffy_recipe_dispatch_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_dispatch_notifier.dart';
import 'package:casdon/modules/recipe/data/model/recipe_ecoprotocol_model.dart';

import 'package:casdon/modules/recipe/ui/widgets/cooking_device_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

class CookingSettingContent extends ConsumerStatefulWidget {
  final String recipeId;
  final String? devId;
  final bool isMiffy;
  final void Function(ThingSmartDeviceModel devModel) onConfirm;

  const CookingSettingContent({
    super.key,
    required this.recipeId,
    this.devId,
    required this.isMiffy,
    required this.onConfirm,
  });

  @override
  ConsumerState<CookingSettingContent> createState() =>
      _CookingSettingContentState();
}

class _CookingSettingContentState extends ConsumerState<CookingSettingContent> {
  @override
  void initState() {
    super.initState();

    if (widget.isMiffy) {
      Future.microtask(() {
        ref
            .read(miffyRecipeDispatchNotifierProvider.notifier)
            .fetchData(recipeId: widget.recipeId, devId: widget.devId);
      });
    } else {
      Future.microtask(() {
        ref
            .read(recipeDispatchNotifierProvider.notifier)
            .fetchData(recipeId: widget.recipeId, devId: widget.devId);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final dispatchState = widget.isMiffy
        ? ref.watch(miffyRecipeDispatchNotifierProvider)
        : ref.watch(recipeDispatchNotifierProvider);
    return Container(
      height: MediaQuery.of(context).size.height * 0.6,
      decoration: BoxDecoration(
        color: context.colorScheme.surface,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      ),
      child: Column(
        children: [
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.symmetric(vertical: 8),
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: dispatchState.when(
                data: (state) {
                  if (state.devList == null || state.devList!.isEmpty) {
                    return const Center(child: CommonLoadingWidget());
                  }

                  final devList = state.devList;
                  final int selectedIndex = state.devIndex ?? 0;
                  final dev = devList![selectedIndex];
                  final eco = state.ecoModel;

                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildTitle(context),
                      SizedBox(height: 20.h),

                      // 烹饪设备
                      Text(
                        "烹饪设备",
                        style: context.textTheme.headlineMedium!.copyWith(
                          color: context.customColorThemeNonNull.textColor1,
                        ),
                      ),
                      SizedBox(height: 8.h),
                      if (devList != null && devList.isNotEmpty)
                        _buildDeviceItem(devList, selectedIndex, context),
                      SizedBox(height: 20.h),

                      // 烹饪参数
                      if (eco != null)
                        _buildCookingParameterSection(context, eco),

                      const Spacer(),

                      // 底部按钮
                      _buildBottomButtons(context, dev),
                      SizedBox(height: 16.h),
                    ],
                  );
                },
                loading: () => const Center(child: CommonLoadingWidget()),
                error: (err, stack) => Center(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTitle(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: Center(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          child: Text(
            "一键烹饪",
            style: context.textTheme.titleLarge!.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCookingParameterSection(
    BuildContext context,
    RecipeEcoprotocol ecoModel,
  ) {
    final steps = ecoModel.cookParams ?? [];
    if (steps.isEmpty) {
      return const Text("暂无参数信息");
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "烹饪参数",
          style: context.textTheme.headlineMedium!.copyWith(
            color: context.customColorThemeNonNull.textColor1,
          ),
        ),
        SizedBox(height: 8.h),
        // 白底圆角容器
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              SizedBox(height: 6.h),
              ...steps
                  .expand(
                    (step) => step.entries.map(
                      (entry) => _buildCookingParameter(
                        context,
                        entry.key,
                        "${entry.value}",
                        withPadding: true, // 可以去掉每行内部的 padding，让圆角更明显
                      ),
                    ),
                  )
                  .toList(),
              SizedBox(height: 6.h),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildCookingParameter(
    BuildContext context,
    String key,
    String value, {
    bool withPadding = true,
  }) {
    return Container(
      padding: withPadding
          ? EdgeInsets.symmetric(horizontal: 16.w, vertical: 6.h)
          : EdgeInsets.symmetric(vertical: 6.h),
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Text(
              key,
              style: context.textTheme.bodyMedium!.copyWith(
                color: context.customColorThemeNonNull.textColor1,
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Padding(
              padding: EdgeInsets.only(right: 0.w), // 右边距 16
              child: Text(
                value,
                style: context.textTheme.bodyMedium!.copyWith(
                  color: context.customColorThemeNonNull.textColor3,
                ),
                textAlign: TextAlign.right, // 右对齐
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceItem(
    List<ThingSmartDeviceModel> devList,
    int selectIndex,
    BuildContext context,
  ) {
    if (devList.length <= selectIndex) {
      return SizedBox.shrink();
    }
    ThingSmartDeviceModel item = devList[selectIndex];
    return SizedBox(
      height: 66.h,
      child: GestureDetector(
        onTap: () => {_onDeviceSelected(devList, selectIndex)},
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Row(
            children: [
              Container(
                width: 40,
                height: 40,
                margin: const EdgeInsets.all(16),
                child: item.iconUrl.isNotEmpty
                    ? ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.network(
                          item.iconUrl,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) =>
                              Icon(Icons.devices, color: Colors.grey[400]),
                        ),
                      )
                    : Icon(Icons.devices, color: Colors.grey[400]),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(8),
                  child: Text(
                    item.name,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                      color: context.customColorThemeNonNull.textColor1,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey),
              const SizedBox(width: 16),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildBottomButtons(
    BuildContext context,
    ThingSmartDeviceModel? devModel,
  ) {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          Expanded(
            child: PrimaryButton(
              text: '返回',
              borderRadius: 6,
              height: 40.h,
              textColor: context.colorScheme.primary,
              backgroundColor: const Color(0xFFF2F3FF),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: GradientButton(
              text: '开始烹饪',
              borderRadius: 6,
              height: 40.h,
              onPressed: devModel == null
                  ? null
                  : () {
                      _onConfirm(devModel);
                    },
            ),
          ),
        ],
      ),
    );
  }

  void _onDeviceSelected(List<ThingSmartDeviceModel> devList, int index) {
    CommonBottomSheet.show(
      context,
      child: CookingDeviceSelectSheet(
        devices: devList,
        selectedIndex: index,
        onSelected: (value) => {
          if (widget.isMiffy)
            {
              Future.microtask(() {
                ref
                    .read(miffyRecipeDispatchNotifierProvider.notifier)
                    .updateSelectedIndex(value);
              }),
            }
          else
            {
              Future.microtask(() {
                ref
                    .read(recipeDispatchNotifierProvider.notifier)
                    .updateSelectedIndex(value);
              }),
            },
        },
      ),
    );
  }

  void _onConfirm(ThingSmartDeviceModel devModel) async {
    bool ret = false;
    if (widget.isMiffy) {
      Future.microtask(() async {
        ret = await ref
            .read(miffyRecipeDispatchNotifierProvider.notifier)
            .dispatch();
        if (ret == true) {
          widget.onConfirm(devModel);
        }
      });
    } else {
      Future.microtask(() async {
        ret = await ref
            .read(recipeDispatchNotifierProvider.notifier)
            .dispatch();
        if (ret == true) {
          widget.onConfirm(devModel);
        }
      });
    }

    Navigator.pop(context);
  }
}
